<?php
/**
 * Created by PhpStorm.
 * User: mayn
 * Date: 2018/9/6
 * Time: 16:39
 */

namespace app\api\models;

use app\api\core\CreateUuid;
use Cm;
use app\api\core\wechat\wxAction;
use phpDocumentor\Reflection\DocBlock\Tags\Var_;
use yii\log\EmailTarget;

class ReplyModel extends BaseModel
{

    public function  actionSyncConfigKeys()
    {
        $wechat = new wxAction($this->wx_app_id);

        $data = Cm::$db->one("SELECT id, sync_time FROM `scrm_weixin_keywords` where wx_account_id='{$this->wx_account_id}' order by add_time desc ");
        if ($data) {
            if ((int)$data['sync_time']-time() < 7*24*3600) {
                Cm::$res->susess('同步成功!');
            }
        }
        $result = $wechat->getCurrentAutoReplyInfo();

        if ($result) {
            Cm::$db->update('scrm_weixin_account', [
                'is_add_friend_reply_open'=>isset($result['is_add_friend_reply_open']) ? $result['is_add_friend_reply_open'] : 0,
                'is_autoreply_open'=>isset($result['is_autoreply_open']) ? $result['is_autoreply_open'] : 0,
            ], "id='{$this->wx_account_id}'");

            //处理关注后回复
            if (isset($result['add_friend_autoreply_info']) && !empty($result['add_friend_autoreply_info'])) {
                $msg = Cm::$db->one("SELECT id FROM `scrm_weixin_subscribe_reply` where wx_account_id='{$this->wx_account_id}'");
                $subscribeData = $result['add_friend_autoreply_info'];

                $type = $subscribeData['type'];

                $subscribeReply = [
                    'type'=>$type,
                    'content'=>$subscribeData['content'],
                ];
                if ($msg) {
                    Cm::$db->update('scrm_weixin_subscribe_reply', $subscribeReply, "wx_account_id='{$this->wx_account_id}'");
                } else {
                    $subscribeReply['id'] = (new CreateUuid())->toString();
                    $subscribeReply['wx_account_id'] = $this->wx_account_id;
                    Cm::$db->insert('scrm_weixin_subscribe_reply', $subscribeReply);
                }

            }

            if (isset($result['keyword_autoreply_info']) && !empty($result['keyword_autoreply_info']) && is_array($result['keyword_autoreply_info'])) {
                $this->setKeyReplyHistory($result['keyword_autoreply_info']);
            }
        }

        Cm::$res->susess('同步成功!');

    }

    private function setKeyReplyHistory($data)
    {
        if (isset($data['list']) && !empty($data['list']) && is_array($data['list'])) {
            foreach ($data['list'] as $item) {
                $config = [
                    'name'=>trim($item['rule_name']),
                    'keywords'=>$item[''],
                    'wx_account_id'=>$item[''],
                    //0:全匹配、1：半匹配
                    //匹配模式，contain代表消息中含有该关键词即可，equal表示消息内容必须和关键词严格相同
                    'preg'=>$item['keyword_list_info']['match_mode']=='contain' ? 1: 0,
                    'create_time'=>$item['create_time'],
                    'reply_mode'=>$item['reply_mode'],
                    'keywords'=>$item['keyword_list_info']['content'],
                ];

                $key_id = 0;
                $configResult = Cm::$db->one("SELECT id FROM `` where wx_account_id='{$this->wx_account_id}' and `name`='{$config['name']}'");
                if ($configResult) {
                    $key_id = $configResult['id'];
                    Cm::$db->update('scrm_weixin_keywords', $config, "id='{$configResult['id']}'");
                } else {
                    $key_id = (new CreateUuid())->toString();
                    $config['id'] = $key_id;
                    $config['sync_time'] = time()+7*24*3600;
                    $config['add_time'] = date('Y-m-d H:i:s');
                    Cm::$db->insert('scrm_weixin_keywords', $config);
                }

                if (isset($item['reply_list_info']) && !empty($item['reply_list_info']) && is_array($item['reply_list_info'])) {
                    foreach ($item['reply_list_info'] as $row) {
                        $type = $row['type'];
                        if ($type == 'news') {
                            $keyConfig = [
                                //'key_id'=>$key_id,
                                'type'=>$type,
                                'content'=>$row['content'],
                                'is_sync'=>1,
                            ];
                            $configInfo = Cm::$db->one("SELECT id FROM `scrm_weixin_keywords_config` WHERE key_id='{$key_id}' and content='{$keyConfig['content']}' and type='{$type}'");
                            $configInfoId=  0;
                            if ($configInfo) {
                                $configInfoId = $configInfo['id'];
                                Cm::$db->update('scrm_weixin_keywords_config', $keyConfig, "id='{$configInfo['id']}'");
                            } else {
                                $configInfoId = (new CreateUuid())->toString();
                                $keyConfig['key_id'] = $key_id;
                                Cm::$db->insert('scrm_weixin_keywords_config', $keyConfig);
                            }
                            if (isset($row['news_info']['list']) && !empty($row['news_info']['list']) && is_array($row['news_info']['list'])) {
                                foreach ($row['news_info']['list'] as $v) {
                                    $item = [
                                        'title'=>$v['title'],
                                        'author'=>$v['author'],
                                        'digest'=>$v['digest'],
                                        'show_cover'=>$v['show_cover'],
                                        'content_url'=>$v['content_url'],
                                        'cover_url'=>$v['cover_url'],
                                        'source_url'=>$v['source_url'],
                                    ];
                                    $itemResult = Cm::$db->one("SELECT id FROM `scrm_weixin_keywords_config_items` WHERE config_id='{$configInfoId}' AND ".$this->arrayToWhere($item));
                                    if ($itemResult) {
                                        Cm::$db->update('scrm_weixin_keywords_config_items', $item, "config_id='{$itemResult['id']}'");
                                    } else {
                                        $item['config_id'] = $configInfoId;
                                        $item['id'] = (new CreateUuid())->toString();
                                        Cm::$db->insert('scrm_weixin_keywords_config_items', $item);
                                    }
                                }
                            }

                        } else {
                            $keyConfig = [
                                'type'=>$type,
                                'content'=>$row['content'],
                                'is_sync'=>1,
                            ];

                            $configInfo = Cm::$db->one("SELECT id FROM `scrm_weixin_keywords_config` WHERE key_id='{$key_id}' and content='{$keyConfig['content']}' and type='{$type}'");
                            $configInfoId=  0;
                            if ($configInfo) {
                                Cm::$db->update('scrm_weixin_keywords_config', $keyConfig, "key_id='{$key_id}' and content='{$keyConfig['content']}' and type='{$type}'");
                            } else {
                                $configInfoId = (new CreateUuid())->toString();
                                Cm::$db->insert('scrm_weixin_keywords_config', $keyConfig);
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * 转换查询条件
     * @param $data
     * @param string $flag
     * @return string
     */
    public function arrayToWhere($data, $flag=" AND ")
    {
        if (is_array($data)) {
            $where = [];
            foreach ($data as $k=>$v) {
                $where[] = "{$k}='{$v}'";
            }
            if ($where) {
                return implode($flag, $where);
            }
        }
        return $data;
    }
    public function actionConfigKeys()
    {
        $rule_name = Cm::$req->post('rule_name', [ 'title'=>'规则名称']);
        $rule_keys = Cm::$req->post('rule_keys', ['reg' => '/[^,:{}\\[\\]0-9.\-+Eaeflnr-u \n\r\t]/', 'title' => '关键词']);
        $type= Cm::$req->post('type', ['reg' => '/^\w+/', 'title' => '内容类型']);
        $reply_mode= Cm::$req->post('reply_mode', ['reg' => '/^\w+/', 'title' => '回复模式']);
        $content= Cm::$req->post('content', [ 'title' => '回复内容']);

        if (!in_array($type, ['image','video','voice','news','text','template'])) {
            Cm::$res->error('内容类型参数错误');
        }
        if (!in_array($reply_mode, ['reply_all','random_one'])) {
            Cm::$res->error('回复模式参数错误');
        }
        $verJson = $this->verJson($rule_keys);
        if (!$verJson['flag']) {
            Cm::$res->error('无效json格式: 无效参数items');
        }
        $arrayDepth = $verJson['dep'];
        $orderRow = $verJson['list'];
        $items = [];
        switch ((int) $arrayDepth) {
            case 1:
                $items[] = [
                    'key' => $orderRow['key'],
                    'preg' => $orderRow['preg'],
                ];
                break;
            case 2:
                $items = array_map(function ($item) {
                    return [
                        'key' => $item['key'],
                        'preg' => $item['preg'],
                    ];
                }, $orderRow);
                break;
            default:
                Cm::$res->error('invalid json：invalid parameter items');
        }

        $id = (new CreateUuid())->toString();
        $data =[
            'id'=>$id,
            'wx_account_id'=>$this->wx_account_id,
            'name'=>$rule_name,
            'add_time'=>date('Y-m-d H:i:s'),
            'create_time'=>date('Y-m-d H:i:s'),
            'reply_mode'=>$reply_mode,
        ];

        Cm::$db->insert('scrm_weixin_keywords_group', $data);

        foreach ($items as $v) {
            $key_id =  (new CreateUuid())->toString();
            $keys =[
                'id'=>$key_id,
                'wx_account_id'=>$this->wx_account_id,
                'keywords'=>$v['key'],
                'preg'=>(int)$v['preg'],
                'key_id'=>$id,
                'add_time'=>date('Y-m-d H:i:s'),
            ];
            Cm::$db->insert('scrm_weixin_keywords', $keys);
            //插入配置数据
            //scrm_weixin_keywords_config
            $data = [
                'key_id'=>$id,
                'key_item_id'=>$key_id,
                'type'=>$type,
            ];
            if ($type=='text') {
                $data['content']=$content;

            } else {
                $data['media_id']=$content;
                $data['content']=$content;
            }
            $config = Cm::$db->one("SELECT id FROM `scrm_weixin_keywords_config` where key_id='{$id}' and key_item_id='{$key_id}'");
            if ($config) {
                Cm::$db->update('scrm_weixin_keywords_config', $data, "id='{$config['id']}'");
            } else {
                $data['id'] = (new CreateUuid())->toString();
                Cm::$db->insert('scrm_weixin_keywords_config', $data);
            }
        }
        Cm::$res->susess('配置成功！');
    }



    public function actionConfigKeysList()
    {
        $page = (int)Cm::$req->post('page',['reg'=>'/^\d+/', 'title'=>'分页']);
        $page_size = (int)Cm::$req->post('page_size',['reg'=>'/^\d+/', 'title'=>'每页条数', 'null','empty', 'default'=>'15']);
        $keys = Cm::$req->post('keys',['title'=>'关键词', 'null','empty']);

        $sql = "SELECT k.id, k.name,k.reply_mode,k.add_time,c.content,c.type,
        (SELECT GROUP_CONCAT(keywords separator ',') from `scrm_weixin_keywords` WHERE key_id=k.id) as keywords
        FROM `scrm_weixin_keywords_group` as k
        INNER JOIN `scrm_weixin_keywords_config` as c on c.key_id=k.id
        WHERE wx_account_id='{$this->wx_account_id}' ";
        if ($keys) {
            $sql .= " and k.name like '%{$keys}%'";
        }
        $sql .= " GROUP BY k.id ";
        $data = Cm::$db->page($sql, $page, $page_size);

        Cm::$res->susess('success', $data);


    }

    public function actionConfigKeysOne()
    {
        $id = Cm::$req->post('id',['reg'=>'/[a-z0-9A-Z]+/', 'title'=>'规则配置ID']);
        $sql ="SELECT k.id,k.name,k.reply_mode,k.add_time,c.content,c.type
        FROM `scrm_weixin_keywords_group` as k
        INNER JOIN `scrm_weixin_keywords_config` as c on c.key_id=k.id
        WHERE wx_account_id='{$this->wx_account_id}' and k.id='{$id}' GROUP BY k.id";
        $keys = Cm::$db->one($sql);
        if (!$keys) {
            Cm::$res->error('规则配置不存在！');
        }

        $itemSql=  "SELECT id, key_id,keywords,preg FROM `scrm_weixin_keywords` WHERE key_id='{$id}'";
        $items = Cm::$db->all($itemSql);
        if (!$items) {
            $items = [];
        }
        $keys['items'] = $items;

        Cm::$res->susess('success', $keys);


    }
    public function actionConfigKeysDel()
    {
        $id = Cm::$req->post('id', ['reg'=>'/^[0-9A-Za-z]{1,}/', 'title'=>'关键词id']);

        $result = Cm::$db->one("select *from `scrm_weixin_keywords_group` where id='{$id}' and  wx_account_id='{$this->wx_account_id}'");
        if (!$result) {
            Cm::$res->error('关键词配置不存在！');
        }

        Cm::$db->delete('scrm_weixin_keywords_group', "id='{$id}' and  wx_account_id='{$this->wx_account_id}'");
        Cm::$db->delete('scrm_weixin_keywords_config', "key_id='{$id}'");
        Cm::$db->delete('scrm_weixin_keywords', "key_id='{$id}'");

        Cm::$res->susess('删除成功！');
    }

    public function actionConfigKeysUpd()
    {
        $rule_name = Cm::$req->post('rule_name', [ 'title'=>'规则名称', 'null', 'empty']);
        $rule_keys = Cm::$req->post('rule_keys', ['reg' => '/[^,:{}\\[\\]0-9.\-+Eaeflnr-u \n\r\t]/', 'title' => '关键词']);
        $type= Cm::$req->post('type', ['reg' => '/^\w+/', 'title' => '内容类型', 'null', 'empty']);
        $reply_mode= Cm::$req->post('reply_mode', ['reg' => '/^\w+/', 'title' => '回复模式', 'null', 'empty']);
        $content= Cm::$req->post('content', [ 'title' => '回复内容', 'null', 'empty']);
        $id = Cm::$req->post('id', ['reg'=>'/^[0-9A-Za-z]{1,}/', 'title'=>'关键词id']);


        if (!in_array($type, ['image','video','voice','news','text','template'])) {
            Cm::$res->error('内容类型参数错误');
        }
        if (!in_array($reply_mode, ['reply_all','random_one'])) {
            Cm::$res->error('回复模式参数错误');
        }
        $verJson = $this->verJsonUpd($rule_keys);
        if (!$verJson['flag']) {
            Cm::$res->error('无效json格式: 无效参数items');
        }
        $arrayDepth = $verJson['dep'];
        $orderRow = $verJson['list'];
        $items = [];
        switch ((int) $arrayDepth) {
            case 1:
                $items[] = [
                    'id' => $orderRow['id'],
                    'key' => $orderRow['key'],
                    'preg' => $orderRow['preg'],
                ];
                break;
            case 2:
                $items = array_map(function ($item) {
                    return [
                        'id' => $item['id'],
                        'key' => $item['key'],
                        'preg' => $item['preg'],
                    ];
                }, $orderRow);
                break;
            default:
                Cm::$res->error('invalid json：invalid parameter items');
        }


        if (!empty($type)) {
            if (!$content) {
                Cm::$res->error('回复类型修改，回复的内容对应修改');
            }
        }
        if (!in_array($reply_mode, ['reply_all','random_one'])) {
            Cm::$res->error('回复模式参数错误');
        }
        $result = Cm::$db->one("select *from `scrm_weixin_keywords_group` where id='{$id}' and  wx_account_id='{$this->wx_account_id}'");
        if (!$result) {
            Cm::$res->error('关键词配置规则不存在！');
        }

        Cm::$db->update('scrm_weixin_keywords_group', array_filter([
            'name'=>$rule_name,
            'reply_mode'=>$reply_mode,
        ]), "id='{$id}' and  wx_account_id='{$this->wx_account_id}'");

        foreach ($items as $v) {

            $keys =[

                'keywords'=>$v['key'],
                'preg'=>(int)$v['preg'],
            ];
            Cm::$db->update('scrm_weixin_keywords', $keys, "id='{$v['id']}'");
            //插入配置数据
            //scrm_weixin_keywords_config
            $data = [
                'type'=>$type,
            ];
            if ($type=='text') {
                $data['content']=$content;

            } else {
                $data['media_id']=$content;
                $data['content']=$content;
            }
            Cm::$db->update('scrm_weixin_keywords_config', $data, "key_item_id='{$v['id']}'");
        }
        Cm::$res->susess('修改成功！');
    }
    public function actionSubscribeReply()
    {

    }
    public function actionConfigKeysLog()
    {

    }

    public function syncKeyReply($appid)
    {

    }

    /**
     * 判断json是否符合标准
     * @param $items
     * @return array
     */
    private function verJson($items, $flag = false)
    {
        $itemsArray = json_decode($items, true);

        $arrayDepth = 1;
        $errorJson = true;
        if ($itemsArray) {
            $arrayDepth = self::array_depth($itemsArray);
            if ($arrayDepth > 1) {
                foreach ($itemsArray as $row) {
                    $key = array_keys($row);
                    if (!empty($key) && is_array($key)) {

                        if (!in_array('key', $key)) {
                            $errorJson = false;
                        }

                        if (!in_array('preg', $key)) {
                            $errorJson = false;
                        }
                    } else {
                        $errorJson = false;
                    }

                }
            } else {
                $key = array_keys($itemsArray);
                if (!empty($key) && is_array($key)) {

                    if (!in_array('key', $key)) {
                        $errorJson = false;
                    }

                    if (!in_array('preg', $key)) {
                        $errorJson = false;
                    }

                } else {
                    $errorJson = false;
                }
            }
        } else {
            $errorJson = false;
        }

        return [
            'flag' => $errorJson,
            'dep' => $arrayDepth,
            'list' => $itemsArray,
        ];
    }
    private function verJsonUpd($items, $flag = false)
    {
        $itemsArray = json_decode($items, true);

        $arrayDepth = 1;
        $errorJson = true;
        if ($itemsArray) {
            $arrayDepth = self::array_depth($itemsArray);
            if ($arrayDepth > 1) {
                foreach ($itemsArray as $row) {
                    $key = array_keys($row);
                    if (!empty($key) && is_array($key)) {

                        if (!in_array('key', $key)) {
                            $errorJson = false;
                        }
                        if (!in_array('id', $key)) {
                            $errorJson = false;
                        }

                        if (!in_array('preg', $key)) {
                            $errorJson = false;
                        }
                    } else {
                        $errorJson = false;
                    }

                }
            } else {
                $key = array_keys($itemsArray);
                if (!empty($key) && is_array($key)) {

                    if (!in_array('key', $key)) {
                        $errorJson = false;
                    }

                    if (!in_array('preg', $key)) {
                        $errorJson = false;
                    }
                    if (!in_array('id', $key)) {
                        $errorJson = false;
                    }

                } else {
                    $errorJson = false;
                }
            }
        } else {
            $errorJson = false;
        }

        return [
            'flag' => $errorJson,
            'dep' => $arrayDepth,
            'list' => $itemsArray,
        ];
    }
}